import { FilterOperate } from './filter-operate'

/** 分页条件 */
export interface PageCondition {
  pageIndex: number
  pageSize: number
  sortCondition: SortCondition[]
}

/** 排序条件 */
export interface SortCondition {
  field: string
  sort: SortDirection
}

/** 排序规则 */
export enum SortDirection {
  Ascending = 0,
  Descending = 1,
}

/** 组件类型 */
export enum ComponentType {
  Input = 1,
  Select = 2,
  TimeSelect = 3,
  RegionSelect = 4,
}

/**
 *查询规则
 * @export
 * @class FilterRule
 * @param {field}     过滤规则key
 * @param {value}     过滤规则value
 * @param {operate}   过滤规则操作符
 */
export class FilterRule {
  field?: string
  value?: any
  operate?: FilterOperate
  constructor(field?: string, value?: any, operate?: FilterOperate) {
    this.field = field
    this.value = value
    this.operate = operate
  }
}

/**
 *查询对象结构
 * @export
 * @class FilterData
 * @param {field}           查询条件key
 * @param {data}            查询条件value
 * @param {op}              查询条件操作符
 * @param {componentType}   此条查询条件对应的组件类型
 * @param {fieldName}       该条查询条件label名称
 * @param {optionList}      下拉选项
 */
export class FilterData {
  field: string
  op: FilterOperate
  data: any | any[]
  componentType: ComponentType
  fieldName: string
  optionList: any[]

  constructor(
    field: string,
    data: any | any[],
    op: FilterOperate,
    componentType: ComponentType = ComponentType.Input,
    fieldName: string = '',
    optionList: any[] = []
  ) {
    this.field = field
    this.op = op
    this.data = data
    this.componentType = componentType
    this.fieldName = fieldName
    this.optionList = optionList
  }
}

/** 查询参数group */
export class FilterGroup {
  rules: FilterRule[]
  groups: FilterGroup[]
  operate: FilterOperate

  constructor(rules: FilterRule[] = [], groups: FilterGroup[] = [], operate: FilterOperate = FilterOperate.And) {
    this.rules = rules
    this.groups = groups
    this.operate = operate
  }

  /** 添加规则 */
  addRule(field: string, value: any, operate: FilterOperate): void {
    const rule = new FilterRule(field, value, operate)
    const isExist = this.rules.some((item) => item.field === field && item.value === value && item.operate === operate)
    if (!isExist) {
      this.rules.push(rule)
    }
  }
}

/** 分页查询 */
export class PageRequest {
  pageCondition: PageCondition
  filterGroup: FilterGroup

  constructor(pageSize: number = 10) {
    this.pageCondition = {
      pageIndex: 1,
      pageSize,
      sortCondition: [],
    }
    this.filterGroup = new FilterGroup()
  }
}
